package com.gilight.base.filter;


import com.alibaba.fastjson.JSONObject;
import com.gilight.base.base.RepStatusCode;
import com.gilight.base.base.ResultEntity;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 登录拦截器
 *
 * @Author: wuzz
 * @Date 2019/9/2 10:46
 */
public class MyAuthorizationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Enumeration<String> t = httpServletRequest.getHeaderNames();
        while(t.hasMoreElements()){
            String key = t.nextElement();
            System.out.println("key:"+key);
            System.out.println("value:"+httpServletRequest.getHeader(key));
        }
        if (isAjax(request)) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            ResultEntity resultEntity= new ResultEntity();
            resultEntity.setMsg("登录认证失效，请重新登录!");
            resultEntity.setStatus(RepStatusCode.NO_AUTH_ERROR.getCode());
            httpServletResponse.getWriter().write(JSONObject.toJSON(resultEntity).toString());
            throw new RuntimeException("s");
        } else {
            //saveRequestAndRedirectToLogin(request, response);
            /**
             * @Mark 非ajax请求重定向为登录页面
             */
            String url = httpServletRequest.getHeader("referer");
            httpServletResponse.sendRedirect(url);
        }
        return false;


    }

    private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


}
